package com.tpe.model.cloud;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.ejb.AccessTimeout;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;

import com.amazonaws.services.sqs.model.Message;
import com.tpe.model.entity.Grupo;
import com.tpe.model.enums.QueueEnum;
import com.tpe.model.service.GrupoService;
import com.tpe.model.util.JsonUtil;

@Singleton
@Startup
public class VerifyGroupQueue {
	
	private List<Message> messages = new ArrayList<Message>();
	
	@EJB private GrupoService grupoService;

	@Timeout
	@AccessTimeout(value = 3, unit = TimeUnit.MINUTES)
	@Schedule(second="*/30", minute="*", hour="*")
	public void queueChecksGroup() throws Exception {
		messages = QueueUtil.retrieveMessages(QueueEnum.QUEUE_RECEIVE_GROUPS.getUrl());

		for(Message msg : messages){
			Grupo grupo = JsonUtil.grupoToObj(msg.getBody());
			grupo.setAtivo(true);
			grupoService.salvar(grupo);

			QueueUtil.deleteQueueItem(msg, QueueEnum.QUEUE_RECEIVE_GROUPS.getUrl());
		}
	}
}
